/*
 * @(#)UserDao.java 2011
 *
 *
 *  Copyright 2011 classic-commerce
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package ca.ioniq.server.dao;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import ca.ioniq.shared.entity.User;

/**
 * @author: <a href="mailto:richard@ioniq.ca">Richard Mutezintare</a>
 */
public class UserDAO extends GenericDAO<User> {

	@Inject
	public UserDAO(EntityManager em) {
		super(em, User.class);
	}

	public UserDAO() {
		super(User.class);
	}
	
	public int updateUserEmail(User user, String email) {
		String hqlQuery = new String("update User set email = :email where userId = :userId");
		int result = em.createNamedQuery(hqlQuery)
						.setParameter("email", email)
						.setParameter("userId", user.getId())
						.executeUpdate();
		
		return result;
	}
	
	public int updatePassword(User user, String newPassword) {
		User repositoryUser = findById(user.getId());
		repositoryUser.getCredential().setPassword(newPassword);
		update(repositoryUser);
		return 1;
	}

	public List<User> findAll(Long id) {
		Query query = em.createQuery("from user u where u.companyId = :companyId");
		query.setParameter("companyId", id);
		
		@SuppressWarnings("unchecked")
		List<User> result = query.getResultList();
		return result;
	}

    public User findByName(String name) {
		Query query = em.createQuery("from User u where u.userName = :name");
		query.setParameter("name", name);
		if(query.getResultList().size()  != 0)
			return (User) query.getResultList().get(0);
		else return null;
	}

}
